import Vue from 'vue'
import VueRouter from "vue-router";
import {setMutation, getGetter} from "@/util/store.js";
import {menu} from "@/init/menu.js";

let methods = ['push', 'replace', 'go']
function overrideMethod(methods) {
    for (let method of methods) {
        let originMethod = VueRouter.prototype[method]
        VueRouter.prototype[method] = async function (...args) {
            try {
                return await originMethod.call(this, ...args)
            } catch {}
        }
    }
}
overrideMethod(methods)

Vue.use(VueRouter)

function addRouteFunction(routeList) {
    for (let route of routeList) {
        if (route.children) {
            addRouteFunction(route.children)
        }
        route.props = (route) => {
            return {
                params: (route.params && Object.keys(route.params).length > 0) ? route.params : undefined
            }
        }
    }
}

let context = require.context('@/router', true, /\.js$/)
let keys = context.keys()
let routeLists = []
let notFoundKey = ''
for (let key of keys) {
    if (key.includes('not-found')) {
        notFoundKey = key
        continue
    }
    let routeList = context(key).routeList
    addRouteFunction(routeList)
    routeLists = [...routeLists, ...routeList]
}
let routeList = context(notFoundKey).routeList
addRouteFunction(routeList)
routeLists = [...routeLists, ...routeList]
let router = new VueRouter(
    {
        mode: 'history',
        routes: routeLists
    }
)

function getBreadcrumb(name) {
    let result = []
    function sub(list) {
        for (let item of list) {
            if (item.routeName === name) {
                result.push({
                    name: item.name,
                    routeName: item.routeName
                })
                return result
            }
            if (item.children) {
                result.push({
                    name: item.name,
                    routeName: item.routeName
                })
                return sub(item.children)
            }
        }
    }
    return sub(menu)
}

function setTag(name) {
    let breadcrumb = getBreadcrumb(name)
    let newTag = {
        name: breadcrumb.map(item => item.name).join('/'),
        routeName: breadcrumb.pop().routeName
    }
    console.log(newTag)
    let tags = getGetter('tag', 'getTags')
    let oldTag = tags.find((item) => {
        return item.routeName === name
    })
    if (oldTag) {
        setMutation('tag', 'setCurrentTag', oldTag)
    } else {
        tags.push(newTag)
        setMutation('tag', 'setTags', tags)
        setMutation('tag', 'setCurrentTag', newTag)
    }
}

router.beforeEach(async (to, from, next) => {
    if (from.name === to.name) {
        next(false)
    }
    let token = sessionStorage.getItem('token')
    if (!token && to.name !== 'login') {
        next({name: 'login', replace: true})
    } else if (token && to.name === 'login') {
        next({...from, replace: true})
    } else {
        setMutation('menu', 'setCurrentRouteName', to.name)
        if (to.name !== 'login') {
            setMutation('top', 'setBreadcrumb', getBreadcrumb(to.name))
            setTag(to.name)
        }
        next()
    }
})

export {router}